import Taro from '@tarojs/taro'
import { HttpStates, SuccessCallbackResult, ResponseSuccessFun } from './interface'
// 响应成功拦截
export function responseSuccessFun(
  res: SuccessCallbackResult,
  noShowDefaultError: boolean
): ResponseSuccessFun {
  Taro.hideLoading()
  const result = res.data
  const state = result.code || result.Result || result.ok

  switch (state) {
    case '0':
      return result || {}
    case true:
      return result || {}
    case '2008':
      Taro.removeStorageSync('userInfo')
      Taro.removeStorageSync('token')
      Taro.reLaunch({ url: '/pages/Login/index' })
    default:
      // 业务中还会有一些特殊 code 逻辑，我们可以在这里做统一处理，也可以下方它们到业务层
      const message = result.message || result.Msg || result.err.msg || '服务器错误'
      if (!noShowDefaultError) {
        Taro.showToast({
          title: message,
          icon: 'none',
          duration: 2000
        })
      }
      return Promise.reject(result)
  }
}
// 响应失败拦截
export function responseFailFun(err) {
  Taro.hideLoading()
  if (err && err.status) {
    switch (err.status) {
      case HttpStates.RESERROR:
        err.message = '请求错误'
        break

      case HttpStates.UNAUTHORIZED:
        err.message = '未授权，请登录'
        break

      case HttpStates.ACCESSDENIED:
        err.message = '拒绝访问'
        break

      case HttpStates.ADDRESSERROR:
        err.message = `请求地址出错: ${err.response.config.url}`
        break

      case HttpStates.REQUESTTIMEOUT:
        err.message = '请求超时'
        break

      case HttpStates.SERVERERROR:
        err.message = '服务器内部错误'
        break

      case HttpStates.SERVICENO:
        err.message = '服务未实现'
        break

      case HttpStates.BADGATEWAY:
        err.message = '网关错误'
        break

      case HttpStates.SERVICENOTAV:
        err.message = '服务不可用'
        break

      case HttpStates.GATEWAYTIMEOUT:
        err.message = '网关超时'
        break

      case HttpStates.HTTPVERSIONNO:
        err.message = 'HTTP版本不受支持'
        break

      default:
        err.message = '请求错误'
    }
  }

  Taro.showToast({
    title: err.message || err.errMsg || err.response.statusText,
    icon: 'none',
    duration: 2000
  })
  return Promise.reject(err)
}
